<template>
	<div class="wrapper">
		<el-card>
			<div id="codeEditBox"></div>
			<el-select-v2 v-model="environment" :options="environment_options" placeholder="请选择环境"></el-select-v2>
			<el-select-v2 v-model="database" :options="database_options" placeholder="请选择数据库"></el-select-v2>
			<el-button @click="handleFormat">格式化</el-button>
			<el-button @click="handleResult" type="primary">点击运行</el-button>
		</el-card>

		<el-container>
			<el-header>
				<div style="height:500px">
				</div>
			</el-header>

			<el-main class="nopadding">

				<el-table :data="handleList.slice((currentPage-1)*pageSize,currentPage*pageSize)" table-layout="auto"
						  fit>
					<template v-for="(item,_) in columnList" :key="_">
						<el-table-column :label="item" :prop="item"></el-table-column>
					</template>
				</el-table>
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 30, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="handleList.length">
				</el-pagination>
			</el-main>

		</el-container>
	</div>

</template>

<script>
import * as monaco from 'monaco-editor'
import {ref, toRaw} from 'vue'
import {format} from 'sql-formatter'
import {language as sqlLanguage} from 'monaco-editor/esm/vs/basic-languages/sql/sql.js';
import {ElMessage} from 'element-plus'

export default {
	data() {
		return {
			environment: ref(),
			environment_options: [],
			database: ref(),
			database_options: [],
			editor1: ref(null),
			result: ref("展示运行结果～～～"),
			editorTheme: ref("vs"),
			language: ref("sql"),
			handleList: [],
			columnList: [],
			rowsList: [],
			tablesList: [],
			// 当前页
			currentPage: 1,
			// 每页多少条
			pageSize: 10,
			monacoProviderRef: ref(),
			selectText: ref(),
			value1: ref([]),
		}
	},
	methods: {
		// 每页多少条
		handleSizeChange(val) {
			this.pageSize = val;
		},
		// 当前页
		handleCurrentChange(val) {
			this.currentPage = val;
		},
		handleFormat() {
			// let lan = toRaw(this.editor1.value).getModel().getLanguageId()
			let content = toRaw(this.editor1).getValue()
			toRaw(this.editor1).setValue(format(content))
		},
		completionInit(tableList) {
			this.monacoProviderRef = monaco.languages.registerCompletionItemProvider('sql', {
				provideCompletionItems: function () {
					let suggestions = [];
					sqlLanguage.keywords.forEach(item => {
						suggestions.push({
							label: item,
							kind: monaco.languages.CompletionItemKind.Keyword,
							insertText: item
						});
					})
					sqlLanguage.operators.forEach(item => {
						suggestions.push({
							label: item,
							kind: monaco.languages.CompletionItemKind.Operator,
							insertText: item
						});
					})
					sqlLanguage.builtinFunctions.forEach(item => {
						suggestions.push({
							label: item,
							kind: monaco.languages.CompletionItemKind.Function,
							insertText: item
						});
					})
					sqlLanguage.builtinVariables.forEach(item => {
						suggestions.push({
							label: item,
							kind: monaco.languages.CompletionItemKind.Variable,
							insertText: item
						});
					})
					tableList.forEach(item => {
						suggestions.push({
							label: item,
							kind: monaco.languages.CompletionItemKind.Keyword,
							insertText: item
						});
					})
					return {
						suggestions: suggestions
					};
				},
			});
		},
		handleError(errorMessage) {
			ElMessage({
				showClose: true,
				message: errorMessage,
				type: 'error',
			})
		},
		handleResult() {
			let selectText = toRaw(this.editor1).getModel().getValueInRange(toRaw(this.editor1).getSelection());
			if (selectText.length === 0) {
				selectText = toRaw(this.editor1).getValue()
			}
			const data = {
				"instance_name": this.environment,
				"sql_content": selectText,
				"db_name": this.database
			};
			const that = this;

			this.$API.sql.list.get(data).then(async res => {
				let query_message = ""
				let effect_row = 0
				if (res.status == 1) {
					const errorMessage = res.msg;
					that.handleError(errorMessage);
					query_message = errorMessage
				} else {
					that.columnList = res.data.column_list;
					that.handleList = res.data.rows;
					effect_row = res.data.rows.length;
				}
				let q_result = {
					"username": that.$TOOL.data.get("USER_DATA").username,
					"text": selectText,
					"instance_name": this.environment,
					"db_name": this.database,
					"query_status": res.status,
					"query_message": query_message,
					"effect_row": effect_row,
				}
				console.log(q_result)
				await this.$API.sql.query_log.post(q_result)

			})
		}
	},
	mounted() {
		let errorMessage;
		this.editor1 = monaco.editor.create(document.getElementById('codeEditBox'), {
			value: '', //编辑器初始显示文字
			language: this.language, //语言支持自行查阅demo
			theme: this.editorTheme, //官方自带三种主题vs, hc-black, or vs-dark
			selectOnLineNumbers: false,//显示行号
			roundedSelection: false,
			readOnly: false, // 只读
			cursorStyle: 'line', //光标样式
			automaticLayout: true, //自动布局
			glyphMargin: true, //字形边缘
			useTabStops: false,
			fontSize: 15, //字体大小
			autoIndent: true, //自动布局
			quickSuggestionsDelay: 100, //代码提示延时
		});
		// this.completionInit()
		const that = this;
		try {
			this.$API.sql.envList.get().then(res => {
				if (res.status == 1) {
					errorMessage = res.msg;
					that.handleError(errorMessage);
				} else {
					const obj = res.data; //定义对象
					const arr = []; //定义数组
					for (const i in obj) {
						arr.push(obj[i]);
					}
					this.environment_options = Array.from(arr).map((value) => ({
						value: `${value}`,
						label: `${value}`
					}))
				}
			})
		} catch (error) {
			errorMessage = '请求后端无响应，请联系管理员。';
			that.handleError(errorMessage)
		}
	},
	watch: {
		environment(n) {
			this.database = ref();
			var data = {
				"instance_name": n
			}
			var that = this
			this.$API.sql.dbList.get(data).then(res => {
				if (res.status == 1) {
					var errorMessage = res.msg;
					that.handleError(errorMessage);
				} else {
					this.database_options = Array.from(res.data).map((value) => ({
						value: `${value}`,
						label: `${value}`,
					}))
				}
			})
		},
		database(n, o) {
			let that = this
			let data = {
				"instance_name": this.environment,
				"db_name": n
			}
			this.$API.sql.tableList.get(data).then(res => {
				if (o) {
					that.monacoProviderRef.dispose()
				}
				that.completionInit(res.data)
			})
		}
	}


}
</script>

<style scoped>
.wrapper {
	margin: 20px auto;
}

#codeEditBox {
	width: 100%;
	font-family: Avenir, Helvetica, Arial, sans-serif;
	height: 400px;
	padding: 0;
	overflow: hidden;
	/*margin-bottom: 15px;*/
}

</style>
